package com.tianle.tlapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianle.tlapp.entity.AppUser;
import com.tianle.tlapp.entity.BalanceLog;
import com.tianle.tlapp.handler.CustomException;
import com.tianle.tlapp.mapper.AppUserMapper;
import com.tianle.tlapp.service.AppUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianle.tlapp.service.BalanceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tianle
 * @since 2023-02-16
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {

    @Autowired
    private BalanceLogService logService;

    @Override
    public BigDecimal getUserBalanceById(String id) {
        //判断id是否为空

        //获取用户信息
        AppUser appUser = baseMapper.selectById(id);

        if (appUser == null){
            throw new CustomException(20001,"用户不存在");
        }

        return appUser.getBalance();
    }

    @Override
    @Transactional
    public void userConsume(String id, BigDecimal number) {

        //获取用户信息
        AppUser appUser = baseMapper.selectById(id);
        BigDecimal balance = appUser.getBalance();

        if (appUser == null){
            throw new CustomException(20001,"用户不存在");
        }
        //判断余额是否充足
        if (number.compareTo(balance) == 1){
            throw new CustomException(20001,"用户余额不足");
        }
        //修改余额
        appUser.setBalance(balance.subtract(number));

        baseMapper.updateById(appUser);

        //添加余额变动日志
        BalanceLog balanceLog = new BalanceLog();
        balanceLog.setAlterType(2);
        balanceLog.setAlterNumber(number);
        balanceLog.setUserId(id);
        logService.save(balanceLog);

    }

    @Override
    @Transactional
    public void userRefund(String id, BigDecimal number) {

        //获取用户信息
        AppUser appUser = baseMapper.selectById(id);
        BigDecimal balance = appUser.getBalance();

        if (appUser == null){
            throw new CustomException(20001,"用户不存在");
        }

        //添加用户余额
        appUser.setBalance(balance.add(number));

        baseMapper.updateById(appUser);

        //添加余额变动日志
        BalanceLog balanceLog = new BalanceLog();
        balanceLog.setAlterType(3);
        balanceLog.setAlterNumber(number);
        balanceLog.setUserId(id);
        logService.save(balanceLog);
    }

    @Override
    public List<BalanceLog> getBalanceLogById(String id) {

        //条件构造器
        QueryWrapper<BalanceLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id);
        //根据时间排序
        wrapper.orderByDesc("gmt_create");
        //获取集合
        List<BalanceLog> list = logService.list(wrapper);
        return list;
    }
}
